package com.mes.task.manager;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.bstek.dorado.annotation.DataResolver;
import com.bstek.dorado.data.provider.Page;
import com.mes.basicdata.dao.EmployeeDao;
import com.mes.basicdata.dao.OperationDao;
import com.mes.basicdata.dao.PartDao;
import com.mes.basicdata.dao.RoutingDao;
import com.mes.basicdata.dao.RoutingLinkDao;
import com.mes.basicdata.dao.XbomDetailDao;
import com.mes.basicdata.domain.Employee;
import com.mes.basicdata.domain.Operation;
import com.mes.basicdata.domain.Part;
import com.mes.basicdata.domain.Routing;
import com.mes.basicdata.domain.RoutingLink;
import com.mes.basicdata.domain.XbomDetail;
import com.mes.basicdata.manager.PartManager;
import com.mes.common.manager.BasicManager;
import com.mes.common.util.IdentityGenerator;
import com.mes.common.util.SysUtil;
import com.mes.task.manager.iface.IDemandManager;
import com.mes.task.dao.DemandDao;
import com.mes.task.dao.DemandTaskLinkDao;
import com.mes.task.dao.OperationTaskDao;
import com.mes.task.dao.PartTaskDao;
import com.mes.task.dao.PartTaskLinkDao;
import com.mes.task.dao.TaskDao;
import com.mes.task.dao.TaskLinkDao;
import com.mes.task.dao.iface.IDemandLinkDao;
import com.mes.task.domain.Demand;
import com.mes.task.domain.DemandLink;
import com.mes.task.domain.DemandTaskLink;
import com.mes.task.domain.OperationTask;
import com.mes.task.domain.PartTask;
import com.mes.task.domain.PartTaskLink;
import com.mes.task.domain.Task;
import com.mes.task.domain.TaskLink;

@Component
public class DemandManager extends BasicManager<Demand> implements IDemandManager {

	private final static Log log = LogFactory.getLog(DemandManager.class);

	@Autowired
	private DemandDao demandDao;
	@Autowired
	private PartDao partDao;
	@Autowired
	private RoutingDao routingDao;
	@Autowired
	private RoutingLinkDao routingLinkDao;
	@Autowired
	private OperationDao operationDao;
	@Autowired
	private EmployeeDao employeeDao;

	@Autowired
	private XbomDetailDao xbomDetailDao;
	@Autowired
	private PartTaskDao partTaskDao;
	@Autowired
	private OperationTaskDao operationTaskDao;
	@Autowired
	private TaskDao taskDao;
	@Autowired
	private TaskLinkDao taskLinkDao;
	@Autowired
	private DemandTaskLinkDao demandTaskLinkDao;
	@Autowired
	private IDemandLinkDao demandLinkDao;
	@Autowired
	private PartTaskLinkDao partTaskLinkDao;
	@Resource
	private DemandLinkManager demandLinkManager;

	/**
	 * 保存计划，同时做后置处理 1、会将计划对应的任务的管理者保存为计划对应的管理者
	 * 
	 * @param demand
	 * @throws Exception
	 */
	@Override
	public void save(Demand demand) throws Exception {
		super.save(demand);
		// 保存计划的同时，将计划的机长保存至产品的机长字段
		List<DemandTaskLink> dtLinks = demandTaskLinkDao.findByProperty("demandUid", demand.getDemandUid());
		if (!CollectionUtils.isEmpty(dtLinks)) {
			DemandTaskLink dtLink = dtLinks.get(0);
			PartTask partTask = partTaskDao.getById(dtLink.getPartTaskUid());
			if (partTask != null) {
				partTask.setTaskManagerUid(demand.getDemandManagerUid());
				partTaskDao.update(partTask);
			}
		}
	}

	/**
	 * 装配任务分解函数
	 * 
	 * @author
	 * @throws Exception
	 * @see com.mes.task.manager.iface.IDemandManager#aoBreak(com.mes.task.domain.Demand)
	 */
	@Override
	@Transactional()
	public void aoBreak(Demand demand) throws Exception {
		String employeeUid = SysUtil.getSessionEmployeeUid();
		Employee employee = employeeDao.getById(employeeUid);

		Part part = partDao.getById(demand.getPartUid());
		// 获取装配主生产计划对应的总工艺路线
		Routing routing = routingDao.getById(demand.getRoutingUid());
		if (routing == null) {
			routing = routingDao.getDefaultRouting(demand.getPartUid(), employee.getDeptUid());
			if (routing == null) {
				return;
			}
		}
		// 生成大产品的装配生产任务
		PartTask task = new PartTask();
		task.setUuid(String.valueOf(IdentityGenerator.GetIdentityLong()));
		task.setPartUid(demand.getPartUid());
		task.setTaskName(demand.getPart().getPartName());
		task.setLateFinish(demand.getLateFinish());
		task.setModel(demand.getModel());
		// task.setPriority(demand.getPriority().intValue());
		task.setBatchNum(demand.getBatchNum());
		task.setTaskId(demand.getDemandId());
		task.setMasterShopUid(demand.getMasterShopUid());
		task.setDeptUid(demand.getMasterShopUid());
		task.setTaskType(PartTask.TASKTYPE_VIRTUAL_DEMAND);
		task.setDueQty(demand.getDueQty());
		task.setPlanQty(demand.getDueQty());
		task.setCompletePercent(0f);
		task.setRoutingUid(routing.getRoutingUid());
		task.setTaskWork(routing.getTotalWork());
		task.setTaskManagerUid(demand.getDemandManagerUid());
		partTaskDao.add(task);

		// 生成装配产品计划与装配产品任务关联关系
		DemandTaskLink dtLink = new DemandTaskLink();
		dtLink.setDemandUid(demand.getDemandUid());
		dtLink.setPartTaskUid(task.getTaskUid());
		dtLink.setLinkQty(task.getPlanQty());
		dtLink.setLockLevel(DemandTaskLink.LOCKLEVEL_LOCKED);
		dtLink.setDependType("1");
		dtLink.setIsInEffect(DemandTaskLink.ISINEFFECT_IS);
		dtLink.setUuid(IdentityGenerator.GetIdentityUUID());
		demandTaskLinkDao.add(dtLink);

		// 生成工序任务
		this.generateOperationTask(task);
		// 生成组件任务
		this.generatePartTask(routing.getRoutingUid(), demand.getPartUid(), task);

		// 设置产品任务总的额定工时
		List<Task> Tasks = taskDao.findByProperty("parentTaskUid", task.getTaskUid());
		float taskWork = 0;
		for (Task task2 : Tasks) {
			taskWork = taskWork + (task2.getTaskWork() == null ? 0 : task2.getTaskWork());
		}
		task.setTaskWork(taskWork);
		partTaskDao.update(task);

		// 根据AO链接模板生成AO链接
		this.generateAOTaskLinks(routing.getRoutingUid(), demand.getBatchNum());

		// 设置计划状态
		demand.setIsBreak(true);
		demand.setDemandState(Demand.DEMANDSTATE_STARTED);
		demandDao.update(demand);

	}

	private void generateAOTaskLinks(String routingUid, String batchNum) throws Exception {

		List<RoutingLink> routingLinks = routingLinkDao.findByProperty("routingUid", routingUid);
		for (RoutingLink routingLink : routingLinks) {
			List<PartTask> prePartTaskList = partTaskDao.getAOTasksByRoutingUid(routingLink.getPredRoutingUid(),
					batchNum);
			List<PartTask> sucPartTaskList = partTaskDao.getAOTasksByRoutingUid(routingLink.getSuccRoutingUid(),
					batchNum);
			if (!CollectionUtils.isEmpty(prePartTaskList) && !CollectionUtils.isEmpty(sucPartTaskList)) {
				PartTaskLink partTaskLink = new PartTaskLink();
				partTaskLink.setUuid(IdentityGenerator.GetIdentityUUID());
				partTaskLink.setPredPartTaskUid(prePartTaskList.get(0).getTaskUid());
				partTaskLink.setSuccPartTaskUid(sucPartTaskList.get(0).getTaskUid());
				partTaskLink.setLinkType(routingLink.getLinkType().longValue());
				partTaskLink.setLinkQty(prePartTaskList.get(0).getPlanQty().doubleValue());
				partTaskLink.setDependType("1");
				partTaskLink.setEffective(true);

				partTaskLinkDao.add(partTaskLink);
			}
		}
	}

	/**
	 * 生成组件任务
	 * 
	 * @param xbomUid
	 *            大工艺唯一号
	 * @param partUid
	 *            父组件唯一号
	 * @param parentTask
	 *            父任务
	 * @throws Exception
	 */
	private void generatePartTask(String xbomUid, String partUid, PartTask parentTask) throws Exception {
		// 按照父组件唯一号从xbomdetail中获取对应BOM信息
		List<XbomDetail> xList = xbomDetailDao.getByXbomUidAndParentPartUid(xbomUid, partUid);
		if (!CollectionUtils.isEmpty(xList)) {
			for (XbomDetail xbomDetail : xList) {
				// 获取子组件的工艺，没有工艺就新生成一条
				if (StringUtils.isBlank(xbomDetail.getSubXbomUid())) {

					Routing subRouting = new Routing();
					subRouting.setPartUid(xbomDetail.getChildPartUid());
					subRouting.setRoutingUid(IdentityGenerator.GetIdentityUUID());
					subRouting.setVersionId(xbomDetail.getChildPartUid() + "-1.0");
					routingDao.add(subRouting);
					xbomDetail.setSubXbomUid(subRouting.getRoutingUid());
				} else {
					Routing routing = routingDao.getById(xbomDetail.getSubXbomUid());
					if (routing == null) {
						List<Routing> routings = routingDao.findByProperty("partUid", xbomDetail.getChildPartUid());
						if (!CollectionUtils.isEmpty(routings)) {
							routing = routings.get(0);
							xbomDetail.setSubXbomUid(routing.getRoutingUid());
						} else {
							continue;
						}
					}
				}

				// 生成子组件任务
				PartTask task = new PartTask();
				task.setUuid(String.valueOf(IdentityGenerator.GetIdentityLong()));
				task.setPartUid(xbomDetail.getChildPartUid());
				task.setLateFinish(parentTask.getLateFinish());
				task.setModel(parentTask.getModel());
				task.setTaskName(xbomDetail.getChildPart().getPartName());
				// task.setPriority(demand.getPriority().intValue());
				task.setBatchNum(parentTask.getBatchNum());
				task.setTaskId(parentTask.getTaskId());
				task.setMasterShopUid(parentTask.getMasterShopUid());
				task.setDeptUid(parentTask.getMasterShopUid());
				task.setTaskType(PartTask.TASKTYPE_VIRTUAL_PART);
				task.setDueQty(parentTask.getDueQty() * xbomDetail.getChildQty());
				task.setPlanQty(parentTask.getDueQty() * xbomDetail.getChildQty());
				task.setCompletePercent(0f);
				task.setRoutingUid(xbomDetail.getSubXbomUid());
				task.setParentTaskUid(parentTask.getTaskUid());
				partTaskDao.add(task);

				// 生成子组件的工序任务
				this.generateOperationTask(task);

				// 生成子组件下级的组件任务（递归遍历）
				this.generatePartTask(xbomDetail.getXbomUid(), xbomDetail.getChildPartUid(), task);

				// 设置组件的额定工时
				List<Task> Tasks = taskDao.findByProperty("parentTaskUid", task.getTaskUid());
				float taskWork = 0;
				for (Task task2 : Tasks) {
					taskWork = taskWork + (task2.getTaskWork() == null ? 0 : task2.getTaskWork());
				}
				task.setTaskWork(taskWork);
				partTaskDao.update(task);
			}
		}

	}

	/**
	 * 生成工序任务
	 * 
	 * @param partTask
	 *            组件任务
	 * @throws Exception
	 */
	private void generateOperationTask(PartTask partTask) throws Exception {
		String employeeUid = SysUtil.getSessionEmployeeUid();
		Employee employee = employeeDao.getById(employeeUid);

		// 获取组件任务工艺，如不存在获取其缺省工艺
		Routing routing = routingDao.getById(partTask.getRoutingUid());

		if (routing == null) {
			routing = routingDao.getDefaultRouting(partTask.getPartUid(), employee.getDeptUid());
			if (routing == null) {
				return;
			}
		}
		// 获取工艺工序
		List<Operation> operationList = this.operationDao.getOperationListByRoutingUid(routing.getRoutingUid());
		// 按照批架次过滤AO工艺工序
		List<Operation> operations = this.filter(operationList, partTask.getBatchNum());

		for (Operation operation : operations) {
			// 如果为AO工艺工序，则找到其参照工艺和其参照工艺下的普通工序，否则对普通工序生成工序任务
			if (operation.getOperationType().equals(Operation.OPERATION_TYPE_REF)) {
				List<Operation> operationList2 = this.operationDao
						.getOperationListByRoutingUid(operation.getRefRoutingUid());
				Routing refRouting = routingDao.getById(operation.getRefRoutingUid());
				if (!CollectionUtils.isEmpty(operationList2)) {
					// 生成AO零组件任务
					PartTask task = new PartTask();
					task.setUuid(String.valueOf(IdentityGenerator.GetIdentityLong()));
					task.setPartUid(partTask.getPartUid());
					task.setLateFinish(partTask.getLateFinish());
					task.setModel(partTask.getModel());
					task.setTaskName(refRouting.getRoutingName());
					// task.setPriority(demand.getPriority().intValue());
					task.setBatchNum(partTask.getBatchNum());
					task.setTaskId(partTask.getTaskId());
					task.setMasterShopUid(partTask.getMasterShopUid());
					task.setDeptUid(partTask.getMasterShopUid());
					task.setTaskType(PartTask.TASKTYPE_VIRTUAL_AO);
					task.setDueQty(partTask.getDueQty());
					task.setPlanQty(partTask.getDueQty());
					task.setCompletePercent(0f);
					task.setRoutingUid(operation.getRefRoutingUid());
					task.setOpType(refRouting.getOpType());
					task.setParentTaskUid(partTask.getTaskUid());
					partTaskDao.add(task);
					log.info("**************" + task.getRoutingUid());
					// 生成AO工艺对应的工序任务（递归）
					generateOperationTasks(task, operationList2);
					// 设置AO组件任务的额定工时
					List<Task> Tasks = taskDao.findByProperty("parentTaskUid", task.getTaskUid());
					float taskWork = 0;
					for (Task task2 : Tasks) {
						taskWork = taskWork + (task2.getTaskWork() == null ? 0 : task2.getTaskWork());
					}
					task.setTaskWork(taskWork);
					partTaskDao.update(task);
				}
			} else {
				log.info("**************" + partTask.getRoutingUid());
				generateSingleOperationTask(partTask, operation);
			}
		}

	}

	/**
	 * 按批架次过滤工艺工序
	 * 
	 * @param operationList
	 * @param batchNum
	 * @return
	 * @throws Exception
	 */
	private List<Operation> filter(List<Operation> operationList, String batchNum) throws Exception {
		Map<String, Operation> map = new HashMap<String, Operation>();
		List<Routing> routings = new ArrayList<Routing>();
		List<Operation> operations = new ArrayList<Operation>();
		for (Operation operation : operationList) {
			// 判断工序是否为AO工序，是则进行过滤，否则将普通工序添加进列表
			if (operation.getOperationType().equals(Operation.OPERATION_TYPE_REF)) {
				Routing refRouting = routingDao.getById(operation.getRefRoutingUid());
				// 生成参照工艺和AO工艺对应的Map，以便后续计算
				map.put(operation.getRefRoutingUid(), operation);
				routings.add(refRouting);
			} else {
				operations.add(operation);
			}

		}
		// 获取过滤后的AO工艺
		List<Routing> newRoutings = getNewRoutings(routings, batchNum);
		for (Routing routing : newRoutings) {
			operations.add(map.get(routing.getRoutingUid()));
		}

		return operations;

	}

	/**
	 * 获取过滤后的AO工艺
	 * 
	 * @param routings
	 * @param batchNum
	 * @return
	 */
	private List<Routing> getNewRoutings(List<Routing> routings, String batchNum) {
		Map<String, Routing> map = new HashMap<String, Routing>();
		for (Routing routing : routings) {
			// 判断AO工艺是否适应当前架次
			boolean checkFlag = check(routing, batchNum);
			if (checkFlag) {
				// 如果适应当前架次，且Map不存在同一routingId的AO，则放入，否则进行版次比较取较大值（新版次）
				if (map.get(routing.getRoutingId()) != null) {
					Routing existRouting = map.get(routing.getRoutingId());
					if (existRouting.getVersionId().compareTo(routing.getVersionId()) < 0) {
						map.put(routing.getRoutingId(), routing);
					}
				} else {
					map.put(routing.getRoutingId(), routing);
				}
			}

		}
		// 返回map中适应且版次最新的AO工艺
		List<Routing> newRoutings = new ArrayList<Routing>(map.values());

		return newRoutings;
	}

	/**
	 * 判断AO工艺是否适应当前架次
	 * 
	 * @param routing
	 * @param batchNum
	 * @return
	 */
	private boolean check(Routing routing, String batchNum) {

		String routingContignationNumber = routing.getContignationNumber();
		boolean flag = false;
		String[] rules = routingContignationNumber.split(",");
		// 判断规则以，作为分隔，分为"-|+|value"三种形式
		for (String string : rules) {
			if (string.indexOf("-") > 0) {
				String[] fromToStrings = string.split("-");
				String from = fromToStrings[0];
				String to = fromToStrings[1];
				if ((batchNum.compareTo(from) > 0 || batchNum.equals(from))
						&& (batchNum.compareTo(to) < 0 || batchNum.equals(to))) {
					flag = true;
					return flag;
				}
			} else if (string.indexOf("+") > 0) {
				String fromString = string.substring(0, string.indexOf("+"));
				if (batchNum.compareTo(fromString) > 0 || batchNum.equals(fromString)) {
					flag = true;
					return flag;
				}

			} else {
				if (batchNum.equals(string)) {
					flag = true;
					return flag;
				}
			}

		}

		return flag;
	}

	private void generateOperationTasks(PartTask partTask, List<Operation> operationList) throws Exception {
		for (Operation operation : operationList) {
			generateSingleOperationTask(partTask, operation);
		}

		List<OperationTask> operationTasks = this.operationTaskDao.getOperationTasksByPartTaskUid(partTask.getTaskUid(),
				false);
		// if(null == operationTasks) return;
		String predUid = null;
		for (OperationTask operationTask2 : operationTasks) {
			if (!operationTask2.getTaskType().startsWith("2")) {
				continue;
			}
			String succUid = operationTask2.getTaskUid();
			if (predUid != null && succUid != null) {
				TaskLink taskLink = new TaskLink();
				taskLink.setUuid(IdentityGenerator.GetIdentityUUID());
				taskLink.setSuccessorUid(succUid);
				taskLink.setPrecessorUid(predUid);
				taskLink.setLinklag(0l);
				taskLink.setLinkqty(operationTask2.getDueQty().doubleValue());
				taskLink.setLinktype(1l);
				taskLink.setDependtype("0");
				taskLink.setIsineffect(1l);
				taskLinkDao.add(taskLink);
			}
			predUid = operationTask2.getTaskUid();

		}
		partTask.setTaskState(PartTask.TASKSTATE_DISASSEMBLE);
		partTaskDao.update(partTask);
	}

	/**
	 * 生成普通工序任务
	 * 
	 * @param partTask
	 * @param operation
	 * @throws Exception
	 */
	private void generateSingleOperationTask(PartTask partTask, Operation operation) throws Exception {
		OperationTask operationTask = new OperationTask();
		operationTask.setTaskUid(String.valueOf(IdentityGenerator.GetIdentityLong()));
		operationTask.setPartUid(partTask.getPartUid());
		operationTask.setBatchNum(partTask.getBatchNum());
		operationTask.setTaskId(partTask.getTaskId());
		operationTask.setDeptUid(partTask.getDeptUid());
		operationTask.setMasterShopUid(partTask.getMasterShopUid());
		operationTask.setPriority(partTask.getPriority());
		operationTask.setTaskState(OperationTask.TASKSTATE_READY);
		operationTask.setModel(partTask.getModel());
		operationTask.setParentTaskUid(partTask.getTaskUid());
		operationTask.setPlanQty(partTask.getPlanQty());
		operationTask.setTaskName(operation.getOperationName());
		operationTask.setIsNeedCheck(operation.getIsNeedCheck());
		operationTask.setOperationUid(operation.getUuid());
		operationTask.setOperationId(operation.getOperationId());
		operationTask.setOperationIdDesc(operation.getOperationIdDesc());
		operationTask.setTaskType(operation.getOperationType());
		operationTask.setRoutingUid(partTask.getRoutingUid());
		operationTask.setEstiPreOpTime(operation.getEstiPreOpTime());
		operationTask.setEstiRunTime(operation.getEstiRunTime());
		operationTask.setNotes(operation.getNotes());
		operationTask.setPreOpTime(operation.getPreOpTime() == null ? 0 : operation.getPreOpTime());
		operationTask.setRunTime(operation.getRunTime() == null ? 0 : operation.getRunTime());
		operationTask
				.setTaskWork((operation.getRunTime() == null ? 0 : operation.getRunTime()) * operationTask.getPlanQty()
						+ (operation.getPreOpTime() == null ? 0 : operation.getPreOpTime()));
		if (operation.getIsCritical() == null || !operation.getIsCritical().booleanValue()) {
			operationTask.setIsCritical(false);
		} else {
			operationTask.setIsCritical(true);
		}
		operationTask.setDueQty(partTask.getDueQty());
		operationTask.setIsSuspended(false);
		operationTask.setIsLocked(false);
		operationTask.setCompleteWork(0f);
		operationTask.setOperationUid(operation.getUuid());

		operationTaskDao.add(operationTask);
	}

	/**
	 * 根据demand的状态，更新后置需求（计划）
	 * 
	 * @param demand
	 * @throws Exception
	 */
	@Override
	public void updateSuccDemands(Demand demand) throws Exception {
		List<DemandLink> demandLinkList = demandLinkDao.findByProperty("predDemandUid", demand.getUuid());
		for (DemandLink demandLink : demandLinkList) {
			Demand succDemand = this.getById(demandLink.getSuccDemandUid());
			List<Demand> dList = this.demandDao.getPredDemands(succDemand.getDemandUid(), null);
			boolean flag = true;
			for (Demand demand2 : dList) {
				if (demand2.getDemandState() != Demand.DEMANDSTATE_FINISHED) {
					flag = false;
					break;
				}
			}
			if (flag) {
				// succDemand.setDemandState(Demand.DEMANDSTATE_ASSEMBLED);
				succDemand.setMaterialState(Demand.DEMANDMATERIALSTATE_READY);
				this.update(succDemand);
			} else {
				succDemand.setMaterialState(Demand.DEMANDMATERIALSTATE_NOTREADY);
				this.update(succDemand);
			}
		}

	}
	
	/**
	 * 通过图号和架次号获取产品demand
	 * @param parentDemandUid
	 * @param parameters
	 * @param page
	 * @return
	 * @throws Exception
	 */
	public List<Demand> getProductDemandsByDrawingIdContignationNumber(String parentDemandUid,
			Map<String, Object> parameters, Page<Demand> page) throws Exception {

		List<Demand> demandList = new ArrayList<Demand>();
		String drawingId = (String) parameters.get("drawingId");
		String contignationNumber = (String) parameters.get("contignationNumber");
		if (contignationNumber != null) {
			contignationNumber = contignationNumber.replace("*", "%");
		}
		if (drawingId != null) {
			drawingId = drawingId.replace("*", "%");
		}
		if (parentDemandUid.equalsIgnoreCase("null")) {
			demandList = demandDao.getProductDemands(drawingId, contignationNumber, page);
		} else {
			demandList = this.getPredAODemands(parentDemandUid);
		}

		return demandList;
	}
	
	/**
	 * 获取指定父指令中装配AO部分的子指令
	 * 
	 * @param succDemandUid
	 *            父指令唯一号
	 * @return 子指令的集合
	 * @throws Exception 
	 */

	public List<Demand> getPredAODemands(String succDemandUid) throws Exception {
		List<Demand> demandList = new LinkedList<Demand>();
		List<DemandLink> demandLinkList = demandLinkManager
				.getPredDemands(succDemandUid);
		if (demandLinkList != null) {
			for (Iterator<DemandLink> iterator = demandLinkList.iterator(); iterator
					.hasNext();) {
				DemandLink demandLink = (DemandLink) iterator.next();
				if (demandLink.getPredDemand().getPart().getPartType().equals(
						"02")) {
					demandList.add(demandLink.getPredDemand());
				}
			}
		}

		Collections.sort(demandList, new Comparator<Demand>() {

			@Override
			public int compare(Demand o1, Demand o2) {
				return o1.getPart().getDrawingId().compareTo(
						o2.getPart().getDrawingId());
			}
		});

		return demandList;
	}

}
